package com.wss.common.wechat.util;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wss.common.context.util.HttpRequestProxyUtil;
import com.wss.common.context.util.SystemConfig;
import com.wss.common.context.util.SystemHelper;
import com.wss.common.wechat.cache.WeChatCache;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 赵飞
 * @version V1.0
 * @Title:
 * @Package com.evermotion.common.wechat.util
 * @Description:
 * @date 2017/8/30
 */
@Component
public class ComponentAccessToken {


	private final Logger logger = Logger.getLogger(ComponentAccessToken.class);

	public void run() {
		logger.info("定时获取ComponentAccessToken开始--->");
		boolean isSuccess = getComponentAccessTokenStrategy();
		if (isSuccess) {
			logger.info("定时刷新ComponentAccessToken结束,刷新状态:成功");
		} else {
			logger.info("定时获取ComponentAccessToken结束,刷新状态:失败");
		}
		logger.info("定时获取ComponentAccessToken结束--->");
	}

	public boolean getComponentAccessTokenStrategy() {
		boolean isSuccess;
		int count = 0;
		do {
			isSuccess = getComponentAccessTokenFromWeChat();
			count++;
			logger.info("第" + count + "次获取ComponentAccessToken：执行结果：" + isSuccess);
			if (!isSuccess) {
				try {
					Thread.sleep(100);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} while (!isSuccess && count < 3);
		if (!isSuccess) {
			logger.info("获取ComponentAccessToken失败，失败次数超过3次！！！！");
			return false;
		} else {
			return true;
		}
	}

	public boolean getComponentAccessTokenFromWeChat() {
		JsonParser jsonParser = new JsonParser();
		Gson gson = new Gson();
		Map<String,String> param = new HashMap<String,String>();
		param.put("component_appid", SystemConfig.getComponentAppId());
		param.put("component_appsecret",SystemConfig.getComponentAppSecret());
		param.put("component_verify_ticket", WeChatCache.getComponentVerifyTicket());
		String jsonStr;
		try {
			jsonStr = HttpRequestProxyUtil.executeJsonParamHttpPost(OpenWeChatInterfaceUtil.getApiComponentToken(),gson.toJson(param));
			if(!SystemHelper.isEmpty(jsonStr)){
				JsonObject jsonObject = jsonParser.parse(jsonStr).getAsJsonObject();
				if(jsonObject.has("component_access_token")){
					WeChatCache.setApiComponentToken(jsonObject.get("component_access_token").getAsString());
					logger.info("定时刷新三方令牌令牌："+ WeChatCache.getApiComponentToken());
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

}
